package com.visionet.waveletData.web.web;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springside.modules.mapper.JsonMapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.google.common.collect.Maps;
import com.visionet.waveletData.web.common.constant.BusinessStatus;
import com.visionet.waveletData.web.common.constant.MobileKey;
import com.visionet.waveletData.web.common.constant.SysConstants;
import com.visionet.waveletData.web.common.utilities.MessageSourceHelper;
import com.visionet.waveletData.web.common.utilities.props.PropsKeys;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;
import com.visionet.waveletData.web.common.utilities.string.GetterUtil;
import com.visionet.waveletData.web.common.utils.PageInfo;
import com.visionet.waveletData.web.service.account.ShiroDbRealm.ShiroUser;
import com.visionet.waveletData.web.webservice.rest.RestException;

@Component
public class BaseController {

	public static String DefaultLocale = GetterUtil.getString(
			PropsUtil.getProperty(PropsKeys.DEFAULT_LOCALE), "zh");
	private static Logger logger = LoggerFactory
			.getLogger(BaseController.class);
	public static final int PAGE_SIZE = 10;

	protected JsonMapper mapper = new JsonMapper();

	public static Map<String, String> GetSuccMap() {
		Map<String, String> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.OK);
		return map;
	}

	private ValueFilter filter = new ValueFilter() {
		@Override
		public Object process(Object obj, String s, Object v) {
			if(v instanceof Date){
				return ((Date) v).getTime();
			}
			if(v instanceof String && v==null) {
                return "";
            }
			
			return v;
		}
	};

	public ResponseEntity<?> responseData(Object data) {
		Map<String, Object> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.OK);
		map.put(MobileKey.MSG, "操作成功");
        if (data != null && !data.equals("")) {
            map.put("data", data);
		}

		

		String jsonstr = JSON.toJSONString(map,filter,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullNumberAsZero,SerializerFeature.WriteNullStringAsEmpty);
		//return new ResponseEntity<String>(jsonstr, HttpStatus.OK);
//		System.out.println(jsonstr);
		return new ResponseEntity<JSON>((JSON)JSON.parse(jsonstr), HttpStatus.OK);
	}

	public ResponseEntity<?> responseErrorData(Object data) {
		Map<String, Object> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.ERROR);
		map.put(MobileKey.MSG, data);
		return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
	}
	public ResponseEntity<?> responseLoginErrorData(Object data) {
		Map<String, Object> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.ACCESSDENIED);
		map.put(MobileKey.MSG, data);
		return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
	}
	public ResponseEntity<?> responseAppKeyErrorData(Object data) {
		Map<String, Object> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.NOTFIND);
		map.put(MobileKey.MSG, data);
		return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
	}
	/**
	 * 
	* @Title: responseUpdateData
	* @Description: 返回需要更新时的数据
	* @param @param data
	* @param @return    设定文件
	* @return ResponseEntity<?>    返回类型
	* @throws
	 */
	public ResponseEntity<?> responseUpdateData(Object data) {
		Map<String, Object> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.VERSION_UPDATE);
		map.put(MobileKey.MSG, "需要更新");
		if (data != null && !data.equals("")) {
	            map.put("data", data);
			}
		return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
	}

	/**
	 * 给前台返回错误信息
	 * 
	 * @param message
	 * @return
	 */
	public static Map<String, String> GetErrorMap(String message) {
		Map<String, String> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.ERROR);
		map.put(MobileKey.MSG, message);
		return map;
	}

	public static Map<String, String> GetSuccMap(String message) {
		Map<String, String> map = Maps.newHashMap();
		map.put(MobileKey.CODE, BusinessStatus.OK);
		map.put(MobileKey.MSG, message);
		return map;
	}

//	public static void setLocale(String locale) {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (user == null) {
//            return;
//        }
//		user.locale = locale;
//		DefaultLocale = null;
//	}

	public static String getLocale() {
		if (DefaultLocale != null) {
			return DefaultLocale;
		}
		return "zh";
	}

//	public static Long getCurrentOrgId() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (user == null) {
//            return null;
//        }
//		if (hasRole(SysConstants.ADMIN)) {
//			return SysConstants.COMMON_ORG_ID;
//		} else {
//			return user.orgId;
//		}
//	}

//	public static String getCurrentOrgName() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		return user.orgName;
//	}

	/**
	 * 取出Shiro中的当前用户所属公司Id. 当前用户为秘书且代理功能打开时，返回领导id
	 */
	public static String getCurrentUserCompanyId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return "";
        }
		if (isAgency() && user.companyId != null) {
			return user.companyId;
		}
		return user.companyId;
	}
	
	/**
	 * 取出Shiro中的当前用户逻辑Id. 当前用户为秘书且代理功能打开时，返回领导id
	 */
	public static Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return -1l;
        }
		if (isAgency() && user.id != null) {
			return user.id;
		}
		return user.id;
	}

	/**
	 * 取出Shiro中的当前用户真实Id.
	 */
	public static Long getLoginUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return null;
        }
		return user.id;
	}

	/**
	 * 取出Shiro中的当前用户显示姓名. 当前用户为秘书且代理功能打开时，返回领导id
	 */
	public static String getCurrentUserName() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return null;
        }
		if (isAgency()) {
			return user.getUserName();
		}
		return user.getUserName();
	}

	/**
	 * 取出Shiro中的当前用户真实姓名.
	 */
	public static String getLoginUserName() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return null;
        }
		return user.getUserName();
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	public static String getCurrentPhoneNumber() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            return null;
        }
		return user.getUserName();
	}

	/**
	 * 判断当前用户是否有某些角色.
	 * 
	 * @param role
	 * @return
	 */
	public static boolean hasRole(String role) {
		return SecurityUtils.getSubject().hasRole(role);
	}

	/**
	 * 判断当前用户是否有某些角色.
	 * 
	 * @param roles
	 * @return
	 */
	public static boolean hasRole(List<String> roles) {
		boolean[] result = SecurityUtils.getSubject().hasRoles(roles);
		for (boolean role : result) {
			if (role) {
				return true;
			}
		}
		return false;
	}

	public static boolean isAdmin() {
		if (SecurityUtils.getSubject().hasRole(SysConstants.ADMIN)) {
			return true;
		} else if (SecurityUtils.getSubject().hasRole(SysConstants.SUBADMIN)) {
			return true;
		}
		return false;
	}

	public static boolean isMeetingAdmin() {
		if (SecurityUtils.getSubject().hasRole(SysConstants.MEETINGADM)) {
			return true;
		}
		return false;
	}

	public static boolean isAppRole() {
		if (SecurityUtils.getSubject().hasRole(SysConstants.USER)) {
			return true;
		} else if (SecurityUtils.getSubject().hasRole(SysConstants.HELPDESK)) {
			return true;
		} else if (SecurityUtils.getSubject().hasRole(SysConstants.AGENCY)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断当前用户是否有某些权限.
	 * 
	 * @param permission
	 * @return
	 */
	public static boolean hasPermission(String permission) {
		return SecurityUtils.getSubject().isPermitted(permission);
	}

	/**
	 * 判断当前用户是否为秘书代领导角色
	 * 
	 * @return
	 */
	public static boolean isAgency() {
		// return hasRole(SysConstants.AGENCY);

		return false;
	}

	/**
	 * 判断当前用户或其领导是否关闭秘书代理功能
	 * 
	 * @return
	 */
//	public static boolean isCloseAgency() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (user == null) {
//            throw new AuthenticationException();
//        }
//		if (user.isLockSec == 1) {
//            return true;
//        } else {
//            return false;
//        }
//	}

	/**
	 * 获取当前用户对应领导/秘书ID
	 * 
	 * @return
	 */
	public static Long getLeaderOrAssistantId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            throw new AuthenticationException();
        }
		return user.id;
	}

	/**
	 * 如果当前用户是秘书并且在代理领导，则返回秘书ID （自己）， 其他则返回null 为了agency_id的设值
	 * 
	 * @return
	 */
	public static Long getAgencyUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
            throw new AuthenticationException();
        }
		if (isAgency()) {
			return user.id;
		} else {
			return null;
		}

	}

//	public static String getCurrentRole() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (user == null) {
//            return null;
//        }
//		return user.getRoleNames();
//	}

//	public static String getUserImgUrl() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (user == null) {
//            return null;
//        }
//		return user.getUserImgUrl();
//	}

	protected void writer(HttpServletResponse res, String obj) throws Exception {
		res.setCharacterEncoding("UTF-8");
		PrintWriter pw = null;
		try {
			pw = res.getWriter();
			pw.print(obj);
		} catch (Exception e) {
			throw e;
		} finally {
			if (null != pw) {
				pw.flush();
				pw.close();
			}
		}
	}

	public static void throwException(String code, String msg) {
		Map<String, String> result = Maps.newHashMap();
		result.put("code", code);
		result.put("msg", msg);
		throw new RestException(result);
	}

	public static void throwException(Map<String, String> result) {
		result.put(BusinessStatus.ERROR, MessageSourceHelper
				.GetMessages("app.web.BaseController.check.fail"));

		throw new RestException(result);
	}

	protected static <T> Page<T> GetPageByList(PageInfo pageInfo,
			List<T> volist, Class<T> destinationClass) {
		if (volist == null || pageInfo == null) {
			return null;
		}

		if (volist.isEmpty()) {
			return new PageImpl<T>(volist, new PageRequest(
					pageInfo.getCurrentPageNumber(), 0, new Sort(
							pageInfo.getSortType(), pageInfo.getSortColumn())),
					0);
		} else {
			return new PageImpl<T>(volist,
					new PageRequest(pageInfo.getCurrentPageNumber(), pageInfo
							.getPageSize(), new Sort(pageInfo.getSortType(),
							pageInfo.getSortColumn())),
					pageInfo.getTotalCount());
		}

	}

	protected static <T> Page<T> GetPageByList(Page<?> page, List<T> volist,
			Class<T> destinationClass) {
		return new PageImpl<T>(volist, new PageRequest(page.getNumber(),
				page.getSize(), page.getSort()), page.getTotalElements());
	}
}
